package com.deuwise.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.Result;
import com.deuwise.common.utils.SpringContextHolder;
import com.deuwise.system.entity.SysLayerField;
import com.deuwise.system.entity.SysLayerFieldOptional;
import com.deuwise.system.entity.SysLayerTitle;
import com.deuwise.system.service.SysLayerFieldOptionalService;
import com.deuwise.system.service.SysLayerFieldService;
import com.deuwise.system.service.SysLayerTitleService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 *@author hezhenhao
 *@date 2020-05-27 13:26:17
 */
@Api(tags = "图层弹窗标题配置模块", description = "图层弹窗标题配置")
@RequestMapping("system/sysLayerTitle")
@RestController()
public class SysLayerTitleController extends AbstractController{
    @Autowired
    private SysLayerTitleService sysLayerTitleService;
    @Autowired
    private SysLayerFieldService sysLayerFieldService;
    @Autowired
    private SysLayerFieldOptionalService sysLayerFieldOptionalService;

    @ApiOperation(value = "获取list", notes = "")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "layerId", value = "图层ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "popupTitle", value = "图层标题", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    public Result<Page<SysLayerTitle>> list(String layerId, String popupTitle){
        Wrapper<SysLayerTitle> wrapper = new EntityWrapper<SysLayerTitle>();
        if(StringUtils.isNotBlank(layerId)){
            wrapper.eq("layer_id", layerId);
        }
        if(StringUtils.isNotBlank(popupTitle)){
            wrapper.eq("popup_title", popupTitle);
        }
        Page<SysLayerTitle> listPage = sysLayerTitleService.selectPage(getPage(SysLayerTitle.class),wrapper);
        for(SysLayerTitle sysLayerTitle : listPage.getRecords()){
            Wrapper<SysLayerField> wrapperField = new EntityWrapper<SysLayerField>();
            wrapperField.orderBy("sort", true);
            wrapperField.eq("title_id", sysLayerTitle.getId());
            List<SysLayerField> list = sysLayerFieldService.selectList(wrapperField);
            for(SysLayerField sysLayerField : list){
                Wrapper<SysLayerFieldOptional> wrapperOptional = new EntityWrapper<SysLayerFieldOptional>();
                wrapperOptional.eq("field_id", sysLayerField.getId());
                sysLayerField.setFieldOptionalList(sysLayerFieldOptionalService.selectList(wrapperOptional));
            }
            sysLayerTitle.setLayerFieldList(list);
        }
        return Result.ok(listPage);
    }

    @ApiOperation(value = "新增或编辑数据")
    @RequestMapping(value = "/insertOrUpdateSyslayerTitle", method = RequestMethod.POST)
    public R insertOrUpdateSyslayerTitle(@RequestBody SysLayerTitle sysLayerTitle){
        boolean isSuccess = false;
        if(null == sysLayerTitle){
            return R.error(200,"新增数据失败，请稍后再试!");
        }
        isSuccess = sysLayerTitleService.insertOrUpdate(sysLayerTitle);
        if (isSuccess) {
            // 先删除
            deleteLayerFile(sysLayerTitle.getId());
            // 重新保存字段
            saveSysLayerField(sysLayerTitle);
            return R.ok();
        } else {
            return R.error(200,"新增数据失败，请稍后再试!");
        }
    }

    @ApiOperation("删除字典")
    @DeleteMapping("/{id}")
    public R delete(@PathVariable("id") String id){
        sysLayerTitleService.deleteById(id);
        deleteLayerFile(id);
        return R.ok();
    }

    /**
     * 删除图层字段及 可选内容
     * @param titleId
     */
    public void deleteLayerFile(String titleId){
        Wrapper<SysLayerField> wrapperField = new EntityWrapper<SysLayerField>();
        wrapperField.eq("title_id", titleId);
        List<SysLayerField> list = sysLayerFieldService.selectList(wrapperField);
        for(SysLayerField sysLayerField : list){
            Wrapper<SysLayerFieldOptional> wrapperOptional = new EntityWrapper<SysLayerFieldOptional>();
            wrapperOptional.eq("field_id", sysLayerField.getId());
            sysLayerFieldOptionalService.delete(wrapperOptional);
        }
        sysLayerFieldService.delete(wrapperField);
    }

    /**
     * 图层字段保存
     * @param sysLayerTitle
     */
    public void saveSysLayerField(SysLayerTitle sysLayerTitle){
        // 图层列表
        List<SysLayerField> fields = sysLayerTitle.getLayerFieldList();
        if(null != fields && 0 < fields.size()){
            for(SysLayerField field : fields){
                field.setTitleId(sysLayerTitle.getId());
                sysLayerFieldService.insert(field);
                // 字段可选项新增
                List<SysLayerFieldOptional> optionals = field.getFieldOptionalList();
                if(null != optionals && 0 < optionals.size()){
                    for(SysLayerFieldOptional optional : optionals){
                        optional.setFieldId(field.getId());
                    }
                    sysLayerFieldOptionalService.insertOrUpdateBatch(optionals);
                }
            }
        }
    }

    @ApiOperation(value = "获取字段列表")
    @GetMapping("/getFieldList")
    public Map<String, Object> getFieldList(String serviceUrl){
        Map<String, Object> resultMap = new HashMap<>(16);
        List<SysLayerField> fieldList = new ArrayList<SysLayerField>();
        SysLayerTitle sysLayerTitle = new SysLayerTitle();
        sysLayerTitle.setServicesUrl(serviceUrl);
        sysLayerTitle.setLayerFieldList(fieldList);
        ServiceAnalysisController analysisController = SpringContextHolder.getBean(ServiceAnalysisController.class);
        R result = analysisController.getFieldList(serviceUrl);

        /*组装popupTemplate结构*/
        List<Map<String,Object>> contents = new ArrayList<>();
        List<Map<String,String>> fieldInfos = new ArrayList<>();
        /*图层字段列表*/
        if(0 == (Integer) result.get("code")){
            /*解析服务字段，构造配置对象信息*/
            List<Map<String, String>> map = (List<Map<String, String>>)result.get("data");
            for(Map<String, String> resMap : map) {
                SysLayerField sysLayerField = new SysLayerField();
                /*字段类型*/
                String fieldType = resMap.get("layerType");
                if (StringUtils.isNotBlank(fieldType)) {
                    /*替换掉esriFieldType，剩下常用字段类型，如String,Integer,Geometry,Double,OID 等*/
                    fieldType = fieldType.trim().replace("esriFieldType", "");
                }
                /*字段名*/
                String field = resMap.get("field");
                /*字段长度*/
                /*String length = resMap.get("length");*/
                /*字段描述（别名）*/
                String alias = resMap.get("alias");
                /*图层名称*/
                /*String layerName = resMap.get("layerName");*/
                /*是否显示*/
                /*String visiable = resMap.get("visiable");*/
                if (StringUtils.isEmpty(field)){
                    continue;
                }
                sysLayerField.setReadonlys(0);
                sysLayerField.setDisplays(0);
                sysLayerField.setAlias(alias);
                sysLayerField.setField(field);
                sysLayerField.setFieldType(fieldType);
                fieldList.add(sysLayerField);

                /*popupTemplate字段对象*/
                Map<String, String> popupMap = new HashMap<>(16);
                popupMap.put("fieldName", field);
                popupMap.put("label", alias);
                fieldInfos.add(popupMap);
            }
            Map<String, Object> contentMap = new HashMap<>(16);
            contentMap.put("fieldInfos", fieldInfos);
            contentMap.put("type", "fields");
            contents.add(contentMap);
        }

        resultMap.put("sysLayerTitle", sysLayerTitle);
        resultMap.put("content", contents);
        return resultMap;
    }
}